package com.enoram.gwt.shared;

import java.util.ArrayList;
import java.util.HashMap;

import com.enoram.gwt.client.LoginServiceAsync;
import com.enoram.gwt.place.SecuredPlace;
import com.enoram.gwt.ui.LoginDialog;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.place.shared.Place;
import com.google.gwt.place.shared.PlaceController;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.PopupPanel;

public class SecurityManager implements Security {

	private LoginServiceAsync loginService;
	private PlaceController placeController;
	
	private ArrayList<Place> securedPlaces = new ArrayList<Place>();
	
	private HashMap<String, ArrayList<Place>> loginTokenMap = new HashMap<String, ArrayList<Place>>();
	
	public SecurityManager(LoginServiceAsync loginService, PlaceController placeController) {
		super();
		this.loginService = loginService;
		this.placeController = placeController;
		
	}



	@Override
	public void secure(final SecuredPlace place) {
		
		final LoginDialog loginDialog = new LoginDialog();
		
		loginDialog.addCloseHandler(new CloseHandler<PopupPanel>() {
			
			@Override
			public void onClose(CloseEvent<PopupPanel> event) {
				
				loginService.login(loginDialog.getUserName(), 
						loginDialog.getPassword(), new AsyncCallback<String>() {
							
							@Override
							public void onSuccess(String result) {
								
								addSecuredPlace(place);
								loginTokenMap.put(result, securedPlaces);
								place.setSecureToken(result);
								placeController.goTo(place);
								
							}
							
							@Override
							public void onFailure(Throwable caught) {
								removePlace(place);
								
							}
						});
			}
		});		
		
		

	}

	protected void addSecuredPlace(Place place){
		if(!securedPlaces.contains(place)){
			securedPlaces.add(place);
		}
	}

	protected void removePlace(Place place){
		
		securedPlaces.remove(place);
	}
	
	@Override
	public boolean isSecured(Place place) {
		//first check if there is already token in token map, use it
		if(loginTokenMap.size()>0){ //already login
			if(!securedPlaces.contains(place)){
				addSecuredPlace(place);
				return true;
			}
		}
		
		return securedPlaces.contains(place);
	}

}
